import {
  PageContainer,
  ProForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
} from "@ant-design/pro-components";
import { Card, Divider, message, Button, Form, Image, Space } from "antd";
import { useEffect, useState } from "react";
import MediaSelectDrawer from "./components/MediaSelectDrawer";
import {
  getSettingInfo,
  saveSystemInfo,
} from "@/services/api/api-parameter-settings";

interface MediaItem {
  id: string;
  name: string;
  url: string;
  coverUrl?: string;
  duration?: number;
}

const ParameterSettings: React.FC = () => {
  const [form] = Form.useForm();
  const [settings, setSettings] = useState<SystemSettings.HighlightConfig>({
    available_transitions: [],
    bgm_path: "",
    bgm_volume: 0.3,
    footer_path: "",
    header_path: "",
    image_duration: 3,
    transition_duration: 0.5,
    transition_effect: "淡入淡出",
  });
  const [mediaItems, setMediaItems] = useState({
    bgm: null as MediaItem | null,
    header: null as MediaItem | null,
    footer: null as MediaItem | null,
  });

  // 控制抽屉显示状态
  const [drawerVisible, setDrawerVisible] = useState({
    header: false,
    footer: false,
    bgm: false,
  });

  const handleSave = async (values: any) => {
    try {
      // 确保媒体路径包含在提交数据中
      const payload = {
        ...values,
        header_path: form.getFieldValue("header_path"),
        footer_path: form.getFieldValue("footer_path"),
        bgm_path: form.getFieldValue("bgm_path"),
      };

      console.log("提交的数据:", payload);
      const res = await saveSystemInfo({
        highlight_config: payload,
      });
      console.log(res);
      getSettingData();
      message.success("配置保存成功");
      return true;
    } catch (error) {
      console.error("Save error:", error);
      message.error("保存失败");
      return false;
    }
  };

  // 处理媒体选择
  const handleMediaSelect =
    (type: "header" | "footer" | "bgm") => (item: MediaItem) => {
      console.log(item);

      setMediaItems((prev) => ({ ...prev, [type]: item }));

      // 更新表单中对应的路径字段
      const pathField = type === "bgm" ? "bgm_path" : `${type}_path`;
      console.log(item);

      form.setFieldsValue({ [pathField]: item.full_path });

      setDrawerVisible((prev) => ({ ...prev, [type]: false }));
      message.success(`${getMediaLabel(type)}已选择`);
    };

  const getMediaLabel = (type: string) => {
    switch (type) {
      case "bgm":
        return "背景音乐";
      case "header":
        return "片头视频";
      case "footer":
        return "片尾视频";
      default:
        return "";
    }
  };

  const getSettingData = async () => {
    try {
      const res = await getSettingInfo();
      console.log("API返回数据:", res);

      // 从返回数据中提取highlight_config
      const highlightConfig = res.data?.highlight_config || {};
      const data = highlightConfig;

      setSettings({
        ...data,
        available_transitions: data.available_transitions || [],
      });

      // 设置表单值 - 确保包含所有需要的字段
      const formValues = {
        default_name: data.default_name || "",
        image_duration: data.image_duration || 3,
        transition_effect: data.transition_effect || "淡入淡出",
        transition_duration: data.transition_duration || 0.5,
        header_path: data.header_path || "",
        footer_path: data.footer_path || "",
        bgm_path: data.bgm_path || "",
        bgm_volume: data.bgm_volume || 0.3,
      };

      console.log("设置表单值:", formValues);
      form.setFieldsValue(formValues);

      // 根据路径设置媒体项
      if (data.bgm_path) {
        setMediaItems((prev) => ({
          ...prev,
          bgm: { id: "1", name: data.bgm_path, url: data.bgm_path },
        }));
        console.log(data.bgm_path);
      }
      if (data.header_path) {
        setMediaItems((prev) => ({
          ...prev,
          header: { id: "2", name: data.header_path, url: data.header_path },
        }));
      }
      if (data.footer_path) {
        setMediaItems((prev) => ({
          ...prev,
          footer: { id: "3", name: data.footer_path, url: data.footer_path },
        }));
      }
    } catch (error) {
      console.error("Failed to fetch settings:", error);
      message.error("获取设置失败");
    }
  };

  useEffect(() => {
    getSettingData();
  }, []);

  return (
    <PageContainer>
      <Card>
        <ProForm
          form={form}
          layout="vertical"
          onFinish={handleSave}
          submitter={{
            resetButtonProps: {
              style: {
                display: "none",
              },
            },
            submitButtonProps: {
              children: "保存设置",
            },
          }}
        >
          <Divider orientation="left" plain>
            基本设置
          </Divider>

          {/* <ProFormText
            name="default_name"
            label="默认集锦名称"
            placeholder="请输入默认集锦名称"
            rules={[{ required: true, message: "请输入默认集锦名称" }]}
            width="md"
          /> */}

          <ProFormDigit
            name="image_duration"
            label="图片显示时长(秒)"
            min={1}
            max={10}
            fieldProps={{ precision: 1, step: 0.5 }}
            width="sm"
          />

          <Divider orientation="left" plain>
            转场设置
          </Divider>

          <ProFormSelect
            name="transition_effect"
            label="转场效果"
            valueEnum={settings.available_transitions.reduce((acc, curr) => {
              acc[curr] = curr;
              return acc;
            }, {} as Record<string, string>)}
            width="sm"
          />

          <ProFormDigit
            name="transition_duration"
            label="转场时长(秒)"
            min={0.1}
            max={3}
            fieldProps={{ precision: 1, step: 0.1 }}
            width="sm"
          />

          <Divider orientation="left" plain>
            媒体设置
          </Divider>

          {/* 隐藏的表单字段，用于存储路径值 */}
          <ProFormText name="header_path" hidden />
          <ProFormText name="footer_path" hidden />
          <ProFormText name="bgm_path" hidden />

          <Form.Item label="片头视频">
            <Space direction="vertical">
              {mediaItems.header && (
                <div style={{ display: "flex", alignItems: "center" }}>
                  {mediaItems.header.coverUrl ? (
                    <Image
                      src={mediaItems.header.coverUrl}
                      width={60}
                      style={{ marginRight: 8, objectFit: "cover" }}
                    />
                  ) : (
                    <span
                      role="img"
                      aria-label="video"
                      style={{ fontSize: 24, marginRight: 8 }}
                    >
                      🎬
                    </span>
                  )}
                  <span>{mediaItems.header.name}</span>
                </div>
              )}
              <Button
                onClick={() =>
                  setDrawerVisible((prev) => ({ ...prev, header: true }))
                }
              >
                {mediaItems.header ? "更换片头视频" : "选择片头视频"}
              </Button>
            </Space>
          </Form.Item>

          <Form.Item label="片尾视频">
            <Space direction="vertical">
              {mediaItems.footer && (
                <div style={{ display: "flex", alignItems: "center" }}>
                  {mediaItems.footer.coverUrl ? (
                    <Image
                      src={mediaItems.footer.coverUrl}
                      width={60}
                      style={{ marginRight: 8, objectFit: "cover" }}
                    />
                  ) : (
                    <span
                      role="img"
                      aria-label="video"
                      style={{ fontSize: 24, marginRight: 8 }}
                    >
                      🎬
                    </span>
                  )}
                  <span>{mediaItems.footer.name}</span>
                </div>
              )}
              <Button
                onClick={() =>
                  setDrawerVisible((prev) => ({ ...prev, footer: true }))
                }
              >
                {mediaItems.footer ? "更换片尾视频" : "选择片尾视频"}
              </Button>
            </Space>
          </Form.Item>

          <Form.Item label="背景音乐">
            <Space direction="vertical">
              {mediaItems.bgm && (
                <div style={{ display: "flex", alignItems: "center" }}>
                  <span
                    role="img"
                    aria-label="music"
                    style={{ fontSize: 24, marginRight: 8 }}
                  >
                    🎵
                  </span>
                  <span>{mediaItems.bgm.name}</span>
                </div>
              )}
              <Button
                onClick={() =>
                  setDrawerVisible((prev) => ({ ...prev, bgm: true }))
                }
              >
                {mediaItems.bgm ? "更换背景音乐" : "选择背景音乐"}
              </Button>
            </Space>
          </Form.Item>

          <ProFormDigit
            name="bgm_volume"
            label="背景音乐音量"
            min={0}
            max={1}
            fieldProps={{ precision: 2, step: 0.05 }}
            width="sm"
            tooltip="0-1之间的小数，如0.5表示50%音量"
          />
        </ProForm>
      </Card>

      {/* 三个抽屉组件 */}
      <MediaSelectDrawer
        visible={drawerVisible.header}
        onClose={() => setDrawerVisible((prev) => ({ ...prev, header: false }))}
        onSelect={handleMediaSelect("header")}
        mediaType="video"
      />
      <MediaSelectDrawer
        visible={drawerVisible.footer}
        onClose={() => setDrawerVisible((prev) => ({ ...prev, footer: false }))}
        onSelect={handleMediaSelect("footer")}
        mediaType="video"
      />
      <MediaSelectDrawer
        visible={drawerVisible.bgm}
        onClose={() => setDrawerVisible((prev) => ({ ...prev, bgm: false }))}
        onSelect={handleMediaSelect("bgm")}
        mediaType="audio"
      />
    </PageContainer>
  );
};

export default ParameterSettings;
